#include "tcpClient.h"
#include "myLog.h"

/**
 * @brief Construct a new Tcp Client:: Tcp Client object
 * 
 */
TcpClient::TcpClient()
{

}

/**
 * @brief Destroy the Tcp Client:: Tcp Client object
 * 
 */
TcpClient::~TcpClient()
{

}

/**
 * @brief 初始化参数
 * 
 * @param groupID 
 * @param ip 
 * @param port 
 */
void TcpClient::init(const string& groupID,const string &ip,const int &port)
{
    groupID_ = groupID;
    ip_ = ip;
    port_ = port;
}

/**
 * @brief 
 * 
 */
void TcpClient::slot_start()
{
    start();
}

/**
 * @brief 尝试连接服务器
 * 
 * @return true 
 * @return false 
 */
bool TcpClient::start()
{
    if(cSocket_ != nullptr)
    {
        cSocket_->close();
        if(cSocket_->state() == QAbstractSocket::ConnectedState)
        {
            cSocket_->disconnectFromHost();
        }
        delete cSocket_;
        cSocket_ = nullptr;
    }

    cSocket_ = new QTcpSocket(this);

    connect(cSocket_,&QTcpSocket::connected,[=]{
        // isConnected_ = true;
        connect(cSocket_,&QTcpSocket::readyRead,this,&TcpClient::slot_read);
    });

    connect(cSocket_,&QAbstractSocket::disconnected,[=]{isConnected_ = false;});

    cSocket_->connectToHost(QString::fromStdString(ip_),port_);
    if(cSocket_->waitForConnected(1000))
    {
        isConnected_ = true;
        QVariantMap stateMap;
        stateMap["type"] = "tcpClient";
        stateMap["state"] = true;
        emit signal_openStatus(stateMap);
    }
    else
    {
        stop();
        isConnected_ = false;
        QVariantMap stateMap;
        stateMap["type"] = "tcpClient";
        stateMap["state"] = false;
        emit signal_openStatus(stateMap);
    }

    return isConnected_;
}

/**
 * @brief 关闭连接
 * 
 * @return true 
 * @return false 
 */
void TcpClient::stop()
{
    if(cSocket_ != nullptr)
    {
        cSocket_->close();
        if(cSocket_->state() == QAbstractSocket::ConnectedState)
        {
            cSocket_->disconnectFromHost();
        }
        delete cSocket_;
        cSocket_ = nullptr;
    }
}

/**
 * @brief 读取数据的槽函数
 * 
 */
void TcpClient::slot_read()
{
    rec_buffer_.clear();
    rec_buffer_ = cSocket_->readAll();
    LOG(INFO)<<"rx msg:"<<QString::fromUtf8(rec_buffer_).toStdString();
    QVariantMap data;
    data["type"] = "tcpClient";
    data["data"] = rec_buffer_;
    emit signal_tcpClient(data);
}


/**
 * @brief 发送数据的槽函数 对外
 * 
 * @param msg 
 */
void TcpClient::slot_write(const QString& msg)
{
    QByteArray data = msg.toUtf8();
    LOG(INFO)<<"tx msg:"<<msg.toUtf8().toStdString();
    write(data);
}

/**
 * @brief TCP发送函数
 * 
 * @param msg 
 */
void TcpClient::write(const QByteArray& msg)
{
    if(isConnected_ && cSocket_ != nullptr && cSocket_->state() == QAbstractSocket::ConnectedState)
    {
        cSocket_->write(msg.toHex());
    }
}